import { _decorator, Component, Node, NodeEventType, sp, tween, v3 } from 'cc';
import { AudioManager } from '../../../framework/manager/AudioManager';
const { ccclass, property } = _decorator;

@ccclass('Balloon')
export class Balloon extends Component {

    private anim: Node

    private in_anim: Node

    private isMoving: boolean

    private ballType: number

    private speed: number



    protected onLoad(): void {
        this.anim = this.node.getChildByName("anim");
        this.in_anim = this.node.getChildByName("in_anim");
        this.isMoving = false;

        this.node.on(Node.EventType.TOUCH_START, (event) => {
            event.stopPropagationImmediate = true;
            // 表示还在产生中，不能搓破
            if (this.isMoving === false) {
                return;
            }
            this.onBalloonBomb()
        }, this)


    }

    start() {

    }

    update(deltaTime: number) {
        if (this.isMoving === false) {
            return;
        }
        let position = this.node.getPosition()
        var sy = deltaTime * this.speed;
        this.node.setPosition(position.x, position.y + sy, position.z)

        if (position.y + sy >= 1024) {
            this.node.removeFromParent();
        }
    }

    public genBalloon(type: number, speed: number) {
        if (type < 1 || type > 7) {
            return;
        }
        AudioManager.Instance.playAudio("boom/sounds/success")

        // idle
        this.isMoving = false;
        this.speed = speed;
        this.ballType = type;

        var ske_com = this.anim.getComponent(sp.Skeleton);
        ske_com.setAnimation(0, "animation_" + type + "_stop", true);
        //  end

        // 播放星星出现的动画
        ske_com = this.in_anim.getComponent(sp.Skeleton);
        ske_com.setAnimation(0, "animation", false);
        // end 

        this.node.setScale(v3(0, 0, 1))
        let scaleNum = Math.random() * 0.4 + 0.1;

        tween(this.node)
            .to(0.5, { scale: v3(scaleNum, scaleNum, 1) }, { easing: "backOut" })
            .call(() => { this.isMoving = true })
            .start()
    }

    onBalloonBomb() {
        AudioManager.Instance.playAudio("boom/sounds/boom")
        // 爆炸动画
        var ske_com = this.anim.getComponent(sp.Skeleton);
        ske_com.setAnimation(0, "animation_" + this.ballType + "_click", false);
        //  end

        // 当爆炸动画结束后，我们应该删除这个节点
        ske_com.setEndListener(() => {
            console.info('remove')
            this.node.removeFromParent();
        })
        // end
    }
}


